#
# @author Wójcik Karol <wojcikk@student.agh.edu.pl>
# @licence http://www.gnu.org/copyleft/gpl.html GNU/GPL
#

class StudyTypesController < ApplicationController
layout 'standard'
before_filter :login_required
before_filter :authorize

  def authorize
    if @session['user'].role != "admin"
	redirect_back_or_default :controller => "error", :action => "info"
    end
  end   

  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @study_type_pages, @study_types = paginate :study_types, :per_page => 10
    @study_types = StudyType.find(:all, :order => 'name')
  end
  
  def show
    @study_type = StudyType.find(params[:id])
    @study_types = StudyType.find(:all)
  end

  def new
    @study_type = StudyType.new
    @study_types = StudyType.find(:all, :order => 'name')  
  end

  def create
    @study_types = StudyType.find(:all, :order => 'id')
    @study_type = StudyType.new(params[:study_type])
    if @study_type.save
      flash[:notice] = 'StudyType was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
   
  end

  def edit
    @study_type = StudyType.find(params[:id])
    @study_types = StudyType.find(:all, :order => 'name')
  end

  def update
    @study_types = StudyType.find(:all, :order => 'name')
    @study_type = StudyType.find(params[:id])
    if @study_type.update_attributes(params[:study_type])
      flash[:notice] = 'StudyType was successfully updated.'
      redirect_to :action => 'show', :id => @study_type
    else
      render :action => 'edit'
    end
  end

  def destroy
    @majors = Major.find(:all, :conditions => ["study_type_id = ?", params[:id]])
    if @majors.blank?
		StudyType.find(params[:id]).destroy
		redirect_to :action => 'list'
	else
		redirect_to :controller => 'error', :action => 'study_type', :code => 'majors', :id => params[:id]
    end
    
  end
end
